package com.jkc.xh.adapters.viewholder;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jkc.xh.R;
import com.jkc.xh.manager.TraderManager;
import com.jkc.xh.models.StockInfoModel;
import com.jkc.xh.network.RestCallBack;
import com.jkc.xh.network.models.MaxBuyNumResponse;
import com.jkc.xh.network.models.RestError;
import com.jkc.xh.network.models.TradeSoldPartRequest;
import com.jkc.xh.utils.Tool;
import com.jkc.xh.views.widget.ToastUtil;

import org.androidannotations.annotations.AfterTextChange;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;

import java.math.BigDecimal;
import java.util.ArrayList;

import retrofit.Call;

/**
 * Created by wangjie28 on 2015/11/13.
 */
@EViewGroup(R.layout.layout_head_sold_part)
public class HeadViewSoldPart extends RelativeLayout {
    @ViewById
    TextView stock_code;
    @ViewById
    TextView stock_name;
    @ViewById
    TextView buy_price1;
    @ViewById
    TextView buy_price2;
    @ViewById
    TextView buy_price3;
    @ViewById
    TextView buy_price4;
    @ViewById
    TextView buy_price5;
    @ViewById
    TextView sale_price1;
    @ViewById
    TextView sale_price2;
    @ViewById
    TextView sale_price3;
    @ViewById
    TextView sale_price4;
    @ViewById
    TextView sale_price5;
    @ViewById
    TextView buy_amount1;
    @ViewById
    TextView buy_amount2;
    @ViewById
    TextView buy_amount3;
    @ViewById
    TextView buy_amount4;
    @ViewById
    TextView buy_amount5;
    @ViewById
    TextView sale_amount1;
    @ViewById
    TextView sale_amount2;
    @ViewById
    TextView sale_amount3;
    @ViewById
    TextView sale_amount4;
    @ViewById
    TextView sale_amount5;
    @ViewById
    TextView close_price;
    @ViewById
    TextView open_price;
    @ViewById
    TextView high_price;
    @ViewById
    TextView low_price;
    @ViewById
    TextView down_price;
    @ViewById
    TextView up_price;

    @ViewById
    TextView last_price;
    @ViewById
    TextView maxcount;
    @ViewById
    EditText priceEnter;
    @ViewById
    EditText maxcountEnter;
    @ViewById
    EditText inputStockCode;

    @ViewById
    RadioGroup countRadioGroup;
    @ViewById
    RadioGroup typeRadioGroup;

    private double currentPrice;
    private long maxBuyCount;
    private long currentBuyCount;
    private String currentCode;
    private String stockDownPrice;
    private String stockUpPrice;
    private String hid;
    private double lastPrice;
    private String buyPrice5;

    /*是否加载成功*/
    private boolean isLoadFinish = false;

    private HeadCallBack headCallBack;

    public HeadViewSoldPart(Context context) {
        super(context);
    }

    public HeadViewSoldPart(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    protected ArrayList<Call> mCallArray = new ArrayList<>();
    protected void addJob(Call call) {
        mCallArray.add(call);
    }

    @Background
    public void clearAllJob() {
        for (Call call : mCallArray) {
            if (call != null) {
                call.cancel();
            };
        }
    }


    @AfterViews
    void bindView() {
        typeRadioGroup.check(R.id.buyEntrustPrice);
        countRadioGroup.check(R.id.countAll);
        countRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (!checkLoadFinish()) {
                    return;
                }
                long nowCount = 0;
                switch (checkedId) {
                    case R.id.countAll:
                        nowCount = maxBuyCount;
                        break;
                    case R.id.count_80:
                        nowCount = (long) (maxBuyCount * 0.8);
                        break;
                    case R.id.count_50:
                        nowCount = (long) (maxBuyCount * 0.5);
                        break;
                    case R.id.count_33:
                        nowCount = (long) (maxBuyCount / 3);
                        break;
                }
                nowCount = nowCount - (nowCount % 100);
                if (nowCount < 100) {
                    nowCount = 100;
                }
                maxcountEnter.setText(nowCount + "");


            }
        });
        typeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.buyEntrustPrice:
                        priceEnter.setText(formatPrice(currentPrice));
                        break;
                    case R.id.buyMarketPrice:
                        priceEnter.setText("");
                        break;
                    case R.id.buyPrice5:
                        priceEnter.setText(buyPrice5);
                        break;
                }
            }
        });
    }

    /**
     * 刷新
     */
    public void reloadStockInfo() {
        if (!TextUtils.isEmpty(currentCode)) {
            loadStockInfo(currentCode, hid);
        }
    }

    public void loadStockInfo(String code, String hid) {
        currentCode = code;
        inputStockCode.setText(currentCode + "");
        this.hid = hid;
        bindView();
        showProgress();
        addJob(TraderManager.queryStockInfoRequest(code, new RestCallBack<StockInfoModel>() {
            @Override
            public void success(StockInfoModel model) {
                stock_code.setText(model.stock_code);
                stock_name.setText(model.stock_name);
                buy_price1.setText(model.buy_price1);
                buy_price2.setText(model.buy_price2);
                buy_price3.setText(model.buy_price3);
                buy_price4.setText(model.buy_price4);
                buy_price5.setText(model.buy_price5);
                sale_price1.setText(model.sale_price1);
                sale_price2.setText(model.sale_price2);
                sale_price3.setText(model.sale_price3);
                sale_price4.setText(model.sale_price4);
                sale_price5.setText(model.sale_price5);
                buy_amount1.setText(model.buy_amount1);
                buy_amount2.setText(model.buy_amount2);
                buy_amount3.setText(model.buy_amount3);
                buy_amount4.setText(model.buy_amount4);
                buy_amount5.setText(model.buy_amount5);
                sale_amount1.setText(model.sale_amount1);
                sale_amount2.setText(model.sale_amount2);
                sale_amount3.setText(model.sale_amount3);
                sale_amount4.setText(model.sale_amount4);
                sale_amount5.setText(model.sale_amount5);

                /*股票价格信息*/
                close_price.setText(formatPrice(model.close_price));
                open_price.setText(formatPrice(model.open_price));
                high_price.setText(formatPrice(model.high_price));
                low_price.setText(formatPrice(model.low_price));
                down_price.setText(formatPrice(model.down_price));
                up_price.setText(formatPrice(model.up_price));
                currentPrice = model.last_price;
                stockUpPrice = model.up_price;
                stockDownPrice = model.down_price;

                lastPrice = model.last_price;
                buyPrice5 = model.buy_price5;
                queryMaxBuyNum(lastPrice + "");
                last_price.setText(Tool.formatPrice(lastPrice));
                priceEnter.setText(Tool.formatPrice(lastPrice));
            }

            @Override
            public void failure(RestError error) {
                closeProgress();
            }
        }));
    }

    public void closeSoftInput() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(priceEnter.getWindowToken(), 0);
    }

    private void queryMaxBuyNum(String price) {
        addJob(TraderManager.querySellPartMaxCount(currentCode, hid, new RestCallBack<MaxBuyNumResponse>() {
            @Override
            public void success(MaxBuyNumResponse response) {
                maxcount.setText(response.maxcount + "");
                maxcountEnter.setText(response.maxcount + "");
                maxBuyCount = response.maxcount;
                currentBuyCount = response.maxcount;
                closeProgress();
                isLoadFinish = true;
            }

            @Override
            public void failure(RestError error) {
                closeProgress();
            }
        }));
    }

    @AfterTextChange(R.id.priceEnter)
    void priceChange(TextView tv, Editable text) {
        String price = text.toString();
        if (!TextUtils.isEmpty(price)) {
            try {
                if (price.contains(".")) {
                    int index = price.indexOf(".");
                    if (index + 3 < price.length()) {
                        price = price.substring(0, index + 3);
                        priceEnter.setText(price);
                        priceEnter.setSelection(price.length());
                    } else {
//                        currentPrice = Double.valueOf(price);
//                        queryMaxBuyNum(price);
                    }
                } else {
//                    currentPrice = Double.valueOf(price);
//                    queryMaxBuyNum(price);
                }

            } catch (Exception e) {

            }
        }
    }

    public String formatPrice(double price) {
        BigDecimal b = new BigDecimal(price);
        double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1 + "";
    }

    public String formatPrice(String price) {
        BigDecimal b = new BigDecimal(price);
        double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1 + "";
    }

    @Click(R.id.priceSub)
    void clickPriceSub() {
        if (!checkLoadFinish()) {
            return;
        }
        if (currentPrice - 0.01 <= 0) {
            ToastUtil.showToastShort("委托价格必须大于0");
            return;
        }
        currentPrice = currentPrice - 0.01;
        priceEnter.setText(formatPrice(currentPrice));
    }

    @Click(R.id.priceAdd)
    void clickPriceAdd() {
        if (!checkLoadFinish()) {
            return;
        }
        currentPrice = currentPrice + 0.01;
        priceEnter.setText(formatPrice(currentPrice));
    }

    @Click(R.id.countAdd)
    void clickCountAdd() {
        if (!checkLoadFinish()) {
            return;
        }
        currentBuyCount = loadCurrentCount();
        if (currentBuyCount + 100 > maxBuyCount) {
            ToastUtil.showToastShort("超过最大购买");
            currentBuyCount = maxBuyCount;
            return;
        }
        currentBuyCount += 100;
        maxcountEnter.setText(currentBuyCount + "");
    }


    @Click(R.id.countSub)
    void clickCountSub() {
        if (!checkLoadFinish()) {
            return;
        }
        currentBuyCount = loadCurrentCount();
        if (currentBuyCount - 100 < 100) {
            ToastUtil.showToastShort("至少100股");
            return;
        }
        currentBuyCount -= 100;
        maxcountEnter.setText(currentBuyCount + "");
    }

    private long loadCurrentCount() {
        String input = maxcountEnter.getText().toString();
        if (TextUtils.isEmpty(input)) {
            currentBuyCount = 0;
        } else {
            currentBuyCount = Long.valueOf(input);
        }
        return currentBuyCount;
    }

    @Click(R.id.buyStock)
    void clickBuyStock() {
        if (!checkLoadFinish()) {
            return;
        }
        long input = loadCurrentCount();
        if (input <= 0) {
            ToastUtil.showToastShort("至少需要卖出100股");
            return;
        }
        if (input > maxBuyCount) {
            ToastUtil.showToastShort("购买失败,当前最大可卖" + maxBuyCount);
            return;
        }
        String currentBuyCount = input + "";

        String currentPrice = priceEnter.getText().toString();
        if (getBuyType() == 2) {
            currentPrice = last_price.getText().toString();
        }
        if (!isIlegalPrice(currentPrice)) {
            return;
        }
        showProgress();
        TradeSoldPartRequest request = new TradeSoldPartRequest(currentCode, currentPrice + "", currentBuyCount, getBuyType(), hid);
        addJob(TraderManager.soldPartStock(request, new RestCallBack<Object>() {
            @Override
            public void success(Object o) {
                closeProgress();
                ToastUtil.showToastShort(R.string.order_success);
            }

            @Override
            public void failure(RestError error) {
                closeProgress();
                ToastUtil.showToastShort(error.msg);
            }

        }));
    }

    /**
     * 输入价格适合合法
     *
     * @return
     */
    public boolean isIlegalPrice(String enterPrice) {
        boolean isEnough = false;
        try {
            Double upPrice = Double.valueOf(stockUpPrice);
            Double downPrice = Double.valueOf(stockDownPrice);
            Double currentPrice = Double.valueOf(enterPrice);
            if (currentPrice <= upPrice && currentPrice >= downPrice) {
                isEnough = true;
            } else {
                ToastUtil.showToastShort("委托价格超过涨停或者跌停价格");
            }
        } catch (Exception e) {

        }
        return isEnough;
    }

    /**
     * 获得委托方式，1=普通，=2市价 整数 枚举:1,2 必填
     *
     * @return
     */
    private int getBuyType() {
        int type = 1;
        switch (typeRadioGroup.getCheckedRadioButtonId()) {
            case R.id.buyEntrustPrice:
                type = 1;
                break;
            case R.id.buyMarketPrice:
                type = 2;
                break;
            case R.id.buyPrice5:
                type = 55;
                break;
        }
        return type;
    }

    /**
     * 检验是否加载股票信息完毕.
     * 并做出提示
     *
     * @return
     */
    private boolean checkLoadFinish() {
        if (!isLoadFinish) {
            ToastUtil.showToastShort("股票信息还没加载完成");
        }
        return isLoadFinish;
    }

    void closeProgress() {
        if (headCallBack != null) {
            headCallBack.loadEnd();
        }
    }

    void showProgress() {
        if (headCallBack != null) {
            headCallBack.loadStart();
        }
    }
    public void setHeadCallBack(HeadCallBack headCallBack) {
        this.headCallBack = headCallBack;
    }

    public interface HeadCallBack {
        void loadStart();

        void loadEnd();
    }
}
